export const useRandomGamesStore = defineStore(
  "RandomGamesStore",
  () => {
    const { newGames, hotGames, classicGames, games } = useGamesData(); // 获取 newGames 数据源
    const randomNewGames = ref<Array<any>>([]); // 存储随机选取的游戏
    const randomHotGames = ref<Array<any>>([]); // 存储随机选取的热门游戏
    const randomClassicGames = ref<Array<any>>([]); // 存储随机选取的推荐游戏
    const lastUpdated = ref<string | null>(null); // 存储最后更新时间
    // 随机选取五个游戏
    const getRandomGames = (datasource: Ref<Array<any>>, count = 5) => {
      if (unref(datasource).length <= count) {
        return unref(datasource); // 如果数据源不足五个，直接返回全部
      }
      const shuffled = [...unref(datasource)].sort(() => 0.5 - Math.random()); // 随机打乱数组
      return shuffled.slice(0, count); // 取前五个
    };

    // 更新每日随机游戏
    const updateDailyRandomGames = () => {
      randomNewGames.value = getRandomGames(newGames, 5);
      randomHotGames.value = getRandomGames(hotGames, 8);
      randomClassicGames.value = getRandomGames(classicGames, 6);
    };

    // 初始化时检查是否需要更新
    onMounted(() => {
      const today = new Date().toDateString();

      if (!unref(lastUpdated) || unref(lastUpdated) !== today) {
        updateDailyRandomGames();
        lastUpdated.value = today; // 更新最后更新时间
      } else {
        // 更新一下数据源 以免数据源属性更新
        const randomNewGameIds = unref(randomNewGames).map((game) => game.id);
        randomNewGames.value = unref(games).filter((game) =>
          randomNewGameIds.includes(game.id)
        );
        const randomHotGameIds = unref(randomHotGames).map((game) => game.id);
        randomHotGames.value = unref(games).filter((game) =>
          randomHotGameIds.includes(game.id)
        );
        const randomClassicGameIds = unref(randomClassicGames).map(
          (game) => game.id
        );
        randomClassicGames.value = unref(games).filter((game) =>
          randomClassicGameIds.includes(game.id)
        );
      }
    });

    return {
      lastUpdated, // 提供最后更新时间
      randomNewGames, // 提供随机新游戏
      randomHotGames, // 提供随机热门游戏
      randomClassicGames, // 提供随机推荐游戏
      updateDailyRandomGames, // 提供手动更新方法
    };
  },
  {
    persist: true, // 启用持久化
  }
);
